from django.http import *
from django.shortcuts import render_to_response
from django.core.paginator import *
from models import *
from forms import *
from authenticator import *
from helper import *
from django.db.models import Q

#---------------------index page------------------------
def index(request):
	#if user is logged in
	if isUserLoggedIn(request):
		if 'logout' in request.GET:
                        return logout(request)
		else:
			return viewHome(request)
	
	if request.method == 'POST':
		if 'login' in request.GET:
			return login(request)
					
		elif 'register' in request.GET:
			return register(request)
	
	loginform = LoginForm()
	registerform = RegisterForm()

	return render_to_response('TextBadger/index.html', {'loginform':loginform, 'registerform':registerform})

#---------------------------login page------------------------------
def login(request):
	loginform = LoginForm(request.POST)
	registerform = RegisterForm()

	if loginform.is_valid():
		#create session
		logIn(request, loginform.cleaned_data['username'])
		return  HttpResponseRedirect(settings.ROOT_URL)
	else:
		return render_to_response('TextBadger/index.html', {'loginform':loginform, 'registerform':registerform})

#---------------------------------logout------------------------------------
def logout(request):
	if isUserLoggedIn(request):
		logOff(request)
	
	return HttpResponseRedirect(settings.ROOT_URL)


#--------------------------register form-----------------------------------
def register(request):
	registerform = RegisterForm(request.POST)
	loginform = LoginForm()

	if registerform.is_valid():
		registerform.save()
			
		#create session
		logIn(request, registerform.cleaned_data['username'])
		return HttpResponseRedirect(settings.ROOT_URL)
	else:
		return render_to_response('TextBadger/index.html', {'registerform':registerform, 'loginform':loginform})


# delete account
@loginRequired
def deleteAccount(request):
	if request.method == 'POST':
		user = getLoggedInUser(request)
		user.account_status = 2
		user.save()
		return logout(request)	
	else:
		return Http500()

# ---------------------- home page -----------------------------
@loginRequired
def viewHome(request):
        user = getLoggedInUser(request)
	return render_to_response("TextBadger/homepage.html", locals())

@loginRequired
def viewUserPage(request):
        user = getLoggedInUser(request)
	try:
		profileuid = int(string.strip(request.GET['uid']))
		profileuser = User.objects.get(id=profileuid)
	except:
		raise Http404

        return render_to_response("TextBadger/userpage.html", locals())

# ---------------------- account page -----------------------------
@loginRequired
def viewAccount(request):
        user = getLoggedInUser(request)
	if request.method == 'POST':
		accountform = AccountForm(request.POST, instance=user)
		if accountform.is_valid():
                        accountform.save()
			accountform = AccountForm(instance=user)
			saved = True
			return render_to_response("TextBadger/account.html", locals())
		else:
			saved = False
                        return render_to_response("TextBadger/account.html", locals())
	else:
		accountform = AccountForm(instance=user)
		return render_to_response("TextBadger/account.html", locals())

# ---------------------- Projects page -----------------------------
@loginRequired
def viewProjects(request):
        user = getLoggedInUser(request)
	user_projects = user.Projects.all()
        return render_to_response("TextBadger/projects.html", locals())

def viewMessages(request):
        user = getLoggedInUser(request)
        return render_to_response("TextBadger/messages.html", locals())

# ---------------------- single project page -----------------------------
@loginRequired
def viewProject(request):
        user = getLoggedInUser(request)

	try:
		pid = request.GET['pid']
		project = Project.objects.get(id=int(pid))
	except:
		raise Http404

	try:
		user_project = user.Projects.get(project=project)
		isHiddenProject = False
		partners = project.Users.exclude(user=user)
	except:
		isHiddenProject = True

	partnerids = ''
	Permissions = Static_User_Permission.objects.all()
	for partner in partners:
		if partnerids == '':
			partnerids = str(partner.id)
		else:
			partnerids = partnerids + "," + str(partner.id)

	# getting all privileges the user has on this project
	if len(user_project.permission.filter(id=1)) > 0:
		isadmin = 1
	if len(user_project.permission.filter(id=2)) > 0:
		readonly = 1
	if len(user_project.permission.filter(id=3)) > 0:
                manageusers = 1
	if len(user_project.permission.filter(id=4)) > 0:
                managecorpus = 1
	if len(user_project.permission.filter(id=5)) > 0:
                managecodebooks = 1
	if len(user_project.permission.filter(id=6)) > 0:
                managetasks = 1
	if len(user_project.permission.filter(id=7)) > 0:
                managejobs = 1
	if len(user_project.permission.filter(id=8)) > 0:
                managereports = 1
	if len(user_project.permission.filter(id=9)) > 0:
                managereportgenerators = 1
	if len(user_project.permission.filter(id=10)) > 0:
                manageclassifieralgos = 1
	if len(user_project.permission.filter(id=11)) > 0:
                managevectorizeralgos = 1
	if len(user_project.permission.filter(id=12)) > 0:
                managecorpusvectors = 1

        usertasks = user.Tasks.filter(project=project)

	return render_to_response("TextBadger/projectpage.html", locals())

def newProject(request):
	user = getLoggedInUser(request)

	try:
		pname = string.strip(request.POST['pname'])
		pdesc = string.strip(request.POST['pdesc'])
		partners = string.strip(request.POST['partners'])

		if pname == '':
			return HttpResponseRedirect(settings.ROOT_URL + 'projects/')

		# create project
		shared_project = user.SharedObjectsOwned.create(SharedObjectType=SharedObjectType.objects.get(id=1), description='Shared Project')	
		project = user.Projects_Created.create(name=pname.capitalize(), description=pdesc, shared_object=shared_project)
		# add user inti this project
		user_project = project.Users.create(user=user)
		# give admin privileges
		user_project.permission.add(Static_User_Permission.objects.get(id=1))

		if partners != '':
			partnersarr = partners.split(',')
			# add all the partners
			for partner in partnersarr:
				partnerobj = User.objects.get(id=int(partner))
				user_project = project.Users.create(user=partnerobj)
        		        # give read privileges in the beginning
	        	        user_project.permission.add(Static_User_Permission.objects.get(id=2))

		return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))
	except:
		return HttpResponseRedirect(settings.ROOT_URL + 'projects/')

@loginRequired
def searchUsers(request):
        user = getLoggedInUser(request)
	try:
		query = string.strip(request.GET['query'])
	except:
		raise Http404

	if 'unique' in request.GET:
		try:
			userobj = User.objects.get(email=query)
			if userobj.id == user.id:
				return HttpResponse("Can't add yourself")
		except:
			raise Http404

		if 'addproj' in request.GET:
			pid = request.GET['addproj']
			try:
				project = Project.objects.get(id=int(pid))
			except:
				raise Http404
	
			try:
				user_project = user.Projects.get(project=project)
			except:
				raise Http404

			if userobj.id not in project.Users.values_list('user', flat=True):
				user_project = project.Users.create(user=userobj)
        	                # give read privileges in the beginning
                	        user_project.permission.add(Static_User_Permission.objects.get(id=2))
			else:
				return HttpResponse("This user is already a partner")

		return HttpResponse("" + str(userobj.id) + "," + userobj.firstname + " " + userobj.lastname)


@loginRequired
def deleteProject(request):
	user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
                project = Project.objects.get(id=int(pid))
        except:
                raise Http404

        # see if the user is a part of the project
        try:
                user_project = user.Projects.get(project=project)

                if len(user_project.permission.filter(id=1)) > 0:
                        # delete project
                        project.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'projects/')

	
@loginRequired
def editProject(request):
	user = getLoggedInUser(request)
        try:
                pid = int(request.POST['pid'])
		pname = string.strip(request.POST['pname'])
		pdesc = string.strip(request.POST['pdesc'])
		psharing = int(request.POST['share'])
		if psharing not in [0, 1, 2]:
			psharing = 0
                project = Project.objects.get(id=int(pid))
        except:
                raise Http404	

	# see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                raise Http404

	if len(user_project.permission.filter(id=1)) > 0:
		project.shared_object.sharing_permission = psharing
		project.shared_object.save()
		project.name = pname
		project.description = pdesc
		project.save()
		return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
	else:
		raise Http404


@loginRequired
def newCorpus(request):
	user = getLoggedInUser(request)
	try:
		pid = request.GET['pid']	
		project = Project.objects.get(id=int(pid))
        except:
                return HttpResponse("failure")

        # see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                return HttpResponse("failure")

	if len(user_project.permission.filter(id=4)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to upload a corpus in this project")

	if request.method == "POST":
		#save
		name = string.strip(request.POST['name'])
                permission = int(request.POST['permission'])
		if permission not in [0, 1, 2]:
                        permission = 0

                xmlfile = request.FILES['corpusfile']
		content_type = xmlfile.content_type
                if content_type:
                    main, sub = content_type.split('/')
                    if not (sub == 'xml'):
                        return HttpResponse('File is not valid XML format')

                # create shared  object
		try:
	                shared_corpora = user.SharedObjectsOwned.create(SharedObjectType=SharedObjectType.objects.get(id=2), description='Shared Corpora', sharing_permission=permission)
        	        project.Corpora.create(name=name, user=user, corpus_file=xmlfile, shared_object=shared_corpora)
		except:
			return HttpResponse("Encountered an Error. Did you upload a valid xml file?")
		
                return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
	else:
		#show page
		return render_to_response("TextBadger/uploadcorpus.html", locals())

@loginRequired
def newCodebook(request):
        user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
                project = Project.objects.get(id=int(pid))
        except:
                return HttpResponse("failure")

        # see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                return HttpResponse("failure")

	if len(user_project.permission.filter(id=5)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to upload a codebook in this project")

	if request.method == "POST":
                #save
                name = string.strip(request.POST['name'])
                permission = int(request.POST['permission'])
                xmlfile = request.FILES['codebookfile']
		content_type = xmlfile.content_type
	        if content_type:
                    main, sub = content_type.split('/')
            	    if not (sub == 'xml'):
                 	return HttpResponse('File is not valid XML format')

		if permission not in [0, 1, 2]:
                        permission = 0
                # create shared  object
                try:
                        shared_codebook = user.SharedObjectsOwned.create(SharedObjectType=SharedObjectType.objects.get(id=3), description='Shared Codebook', sharing_permission=permission)
                        project.Codebooks.create(name=name, user=user, codebook_file=xmlfile, shared_object=shared_codebook, type=1)
                except:
                        return HttpResponse("Encountered an Error. Did you upload a valid xml file?")

                return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
        else:
                #show page
                return render_to_response("TextBadger/uploadcodebook.html", locals())


@loginRequired
def leaveProject(request):
	user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
                project = Project.objects.get(id=int(pid))
        except:
                raise Http404

        # see if the user is a part of the project
       	try:
                user_project = user.Projects.get(project=project)

		if len(user_project.permission.filter(id=1)) > 0:
			# delete project
			project.delete()
		else:
			# leave project
			user_project.delete()
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'projects/')


@loginRequired
def removePartner(request):
	user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
		uid = request.GET['uid']
                project = Project.objects.get(id=int(pid))
		userobj = User.objects.get(id=int(uid))
        except:
                raise Http404

	if user.id == userobj.id:
		return leaveProject(request)		

        # see if the user is a part of the project
        try:
                user_project = user.Projects.get(project=project)
		remove_partner = project.Users.get(user=userobj)
		# admin or manage user permission
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=3)) > 0:
                        # delete partner
                        remove_partner.delete()
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))


@loginRequired
def removeCorpora(request):
        user = getLoggedInUser(request)
        try:
                cid = int(request.GET['cid'])
               	corpora = Corpora.objects.get(id=cid) 
		project = corpora.project
		user_project = user.Projects.get(project=project)
		if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=4)) > 0:
			corpora.delete()
		else:
			raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))

@loginRequired
def removeCodebook(request):
        user = getLoggedInUser(request)
        try:
                cid = int(request.GET['cid'])
                codebook = Codebook.objects.get(id=cid)
                project = codebook.project
                user_project = user.Projects.get(project=project)
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=5)) > 0:
                        codebook.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))


@loginRequired
def editCodebook(request):
	user = getLoggedInUser(request)
        try:
                cid = request.GET['cid']
        	codebook = Codebook.objects.get(id=cid)
                project = codebook.project
                user_project = user.Projects.get(project=project)
	except:
                raise Http404

        if len(user_project.permission.filter(id=5)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to edit codebooks in this project")

        if request.method == "POST":
                #save
                name = string.strip(request.POST['name'])
                permission = int(request.POST['permission'])
		if 'codebookfile' in request.FILES:
	                xmlfile = request.FILES['codebookfile']
			content_type = xmlfile.content_type
	                if content_type:
        	            main, sub = content_type.split('/')
                	    if not (sub == 'xml'):
                        	return HttpResponse('File is not valid XML format')
		else:
			xmlfile = None
                if permission not in [0, 1, 2]:
                        permission = 0
                # create shared  object
                try:
			codebook.name = name
			if xmlfile != None:
				codebook.codebook_file = xmlfile
				codebook.Questions.all().delete()
				codebook.status = 2
			codebook.shared_object.sharing_permission = permission
			codebook.shared_object.save()
			codebook.save()
                except:
                        return HttpResponse("Encountered an Error. Did you upload a valid xml file?")

                return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))
        else:
                #show page
                return render_to_response("TextBadger/editcodebook.html", locals())

@loginRequired
def editCorpora(request):
        user = getLoggedInUser(request)
        try:
                cid = request.GET['cid']
                corpora = Corpora.objects.get(id=cid)
                project = corpora.project
                user_project = user.Projects.get(project=project)
        except:
                raise Http404

        if len(user_project.permission.filter(id=4)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to edit corpora in this project")

        if request.method == "POST":
                #save
                name = string.strip(request.POST['name'])
                permission = int(request.POST['permission'])
	        if 'corpusfile' in request.FILES:
                        xmlfile = request.FILES['corpusfile']
			content_type = xmlfile.content_type
	                if content_type:
        	            main, sub = content_type.split('/')
                	    if not (sub == 'xml'):
                        	return HttpResponse('File is not valid XML format')
                else:
                        xmlfile = None
                if permission not in [0, 1, 2]:
                        permission = 0
                # create shared  object
                try:
                        corpora.name = name
                        if xmlfile != None:
                                corpora.corpus_file = xmlfile
				corpora.Documents.all().delete()
				corpora.status = 2
                        corpora.shared_object.sharing_permission = permission
                        corpora.shared_object.save()
                        corpora.save()
                except:
                        return HttpResponse("Encountered an Error. Did you upload a valid xml file?")

                return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))
        else:
                #show page
                return render_to_response("TextBadger/editcorpora.html", locals())

@loginRequired
def manageUsers(request):
	if request.method == 'POST':
		user = getLoggedInUser(request)
		try:
			upid = int(request.POST['up'])
			add = string.strip(request.POST['add'])
			pid = int(request.POST['pid'])
			pobj = Static_User_Permission.objects.get(id=pid)
			up = User_Project.objects.get(id=upid)
			project = up.project
			user_project = user.Projects.get(project=project)

                	if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=3)) > 0:
				if add == "true":
					if pobj not in up.permission.all():
						up.permission.add(pobj)
				else:
					if pobj in up.permission.all():
						up.permission.remove(pobj)

				return HttpResponse("success")
			else:
				raise Http404
		except:
			raise Http404
	else:
		raise Http404


@loginRequired
def newTask(request):
        user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
                project = Project.objects.get(id=int(pid))
        except:
                return HttpResponse("failure")

        # see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                return HttpResponse("failure")

        if len(user_project.permission.filter(id=6)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to create a task in this project")

        if request.method == "POST":
		# save task
		name = string.strip(request.POST['name'])
		corpora = int(request.POST['corpora'])
		codebook = int(request.POST['codebook'])
		u = int(request.POST['user'])
		corporaobj = project.Corpora.get(id=corpora, status=1)
                codebookobj = project.Codebooks.get(id=codebook, status=1)

		try:
			minr = int(request.POST['min'])
			if minr < 1:
				minr = 1
		except:
			minr = 1
		try:
			maxr = int(request.POST['max'])
			if maxr > corporaobj.num_docs:
				maxr = corporaobj.num_docs
		except:
			maxr = corporaobj.num_docs

		num_docs = maxr - minr + 1

		userobj = project.Users.get(user=User.objects.get(id=u)).user
		task = Task(name=name, project=project, corpus=corporaobj, codebook=codebookobj, user=userobj, assigner=user, num_docs=num_docs, minrange=minr, maxrange=maxr)
		task.save()
		return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
	else:
		users = project.Users.all()
		corporas = project.Corpora.filter(status=1)
		codebooks = project.Codebooks.filter(status=1)
		
		return render_to_response('TextBadger/newtask.html', locals())


@loginRequired
def removeTask(request):
        user = getLoggedInUser(request)
        try:
                tid = int(request.GET['tid'])
		task = Task.objects.get(id=tid)
                project = task.project
                user_project = user.Projects.get(project=project)
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=6)) > 0:
                        task.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))

@loginRequired
def removeJob(request):
        user = getLoggedInUser(request)
        try:
                jid = int(request.GET['jid'])
                job = Job.objects.get(id=jid)
                project = job.project
                user_project = user.Projects.get(project=project)
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=7)) > 0:
                        job.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))

@loginRequired
def removeReport(request):
        user = getLoggedInUser(request)
        try:
                rid = int(request.GET['rid'])
                report = Report.objects.get(id=rid)
                project = report.project
                user_project = user.Projects.get(project=project)
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=8)) > 0:
                        report.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))

@loginRequired
def removeCorpusVector(request):
        user = getLoggedInUser(request)
        try:
                vid = int(request.GET['vid'])
                vector = Corpus_Vector.objects.get(id=vid)
                project = vector.project
                user_project = user.Projects.get(project=project)
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=12)) > 0:
                        vector.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))

@loginRequired
def removeAlgo(request):
        user = getLoggedInUser(request)
        try:
                aid = int(request.GET['aid'])
		type = string.strip(request.GET['type'])
		
		if type == 'v':
                	algo = Vectorizer_Algo.objects.get(id=aid)
			pid = 11
		elif type == 'c':
			algo = Classifier_Algo.objects.get(id=aid)
			pid = 10
		else:
			algo = ReportGenerator.objects.get(id=aid)
			pid = 9

                project = algo.project
                user_project = user.Projects.get(project=project)
                if len(user_project.permission.filter(id=1)) > 0 or len(user_project.permission.filter(id=pid)) > 0:
                        algo.delete()
                else:
                        raise Http404
        except:
                raise Http404

        return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))


@loginRequired
def newJob(request):
        user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
                project = Project.objects.get(id=int(pid))
        except:
                return HttpResponse("failure")

        # see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                return HttpResponse("failure")

        if len(user_project.permission.filter(id=7)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to create a job in this project")

	tasks = project.Tasks.filter(status=1)
	classification_algos = project.Classifiers_Algo_Uploaded.filter(status=1) | Classifier_Algo.objects.filter(status=1, user=None, project=None)
	vectorization_algos = project.Vectorizers_Algo_Uploaded.filter(status=1) | Vectorizer_Algo.objects.filter(status=1, user=None, project=None)
	vectors = project.Vectors.filter(status=1)

        if request.method == "POST":
		# save job
		name = string.strip(request.POST['name'])
		tids = []
		for k, v in request.POST.lists():
			if k == "tid":
				for val in v:
					tids.append(val)

		cid = int(request.POST['cid'])
		vid = int(request.POST['vid'])
		cargs = string.strip(request.POST['carg'])
		vargs = string.strip(request.POST['varg'])
		vector = request.POST['vecid']
		if vector == "0":
			vector = None
		else:
			vector = project.Vectors.get(id=int(vector))

		cobj = Classifier_Algo.objects.get(id=cid, status=1)
		if vector == None:
			vobj = Vectorizer_Algo.objects.get(id=vid, status=1)
		else:
			vobj = None

		job = project.Jobs.create(user=user, name=name, classifier_algo=cobj, vectorizer_algo=vobj, classifier_args=cargs, vectorizer_args=vargs, corpus_vector=vector)
		for tid in tids:
			job.tasks.add(project.Tasks.get(id=int(tid), status=1))
	
		return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
	else:
		return render_to_response('TextBadger/newjob.html', locals())

@loginRequired
def newAlgo(request):
        user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
		type = request.GET['type']
                project = Project.objects.get(id=int(pid))
        except:
                return HttpResponse("failure")

        # see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                return HttpResponse("failure")

	if type == 'r':
		upid = 9
		shid = 7
		desc = 'Shared Report generator Algo'
	elif type == 'c':
		upid = 10
		shid = 5
                desc = 'Shared Classification Algo'
	else:
		upid = 11
		shid = 4
                desc = 'Shared Vectorizer Algo'

        if len(user_project.permission.filter(id=upid)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to upload this algo in this project")

        if request.method == "POST":
		# save algo
		name = string.strip(request.POST['name'])
                permission = int(request.POST['permission'])
                codefile = request.FILES['codefile']
                content_type = codefile.content_type
                if content_type:
                    main, sub = content_type.split('/')
                    if not (main == 'text'):
                        return HttpResponse('Please submit a valid ASCII Text File')

                if permission not in [0, 1, 2]:
                        permission = 0
                # create shared  object
                try:
                        shared_code = user.SharedObjectsOwned.create(SharedObjectType=SharedObjectType.objects.get(id=shid), description=desc, sharing_permission=permission)
			if type == 'r':
	                        project.ReportGenerator_Algo_Uploaded.create(name=name, user=user, filename=codefile, shared_object=shared_code)
			elif type == 'c':
                                project.Classifiers_Algo_Uploaded.create(name=name, user=user, filename=codefile, shared_object=shared_code)
			else:
                                project.Vectorizers_Algo_Uploaded.create(name=name, user=user, filename=codefile, shared_object=shared_code)
                except:
                        return HttpResponse("Encountered an Error. Did you upload a valid code file in ASCII Text format?")

		return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
	else:
		return render_to_response('TextBadger/newalgo.html', locals())

@loginRequired
def newReport(request):
        user = getLoggedInUser(request)
        try:
                pid = request.GET['pid']
                project = Project.objects.get(id=int(pid))
        except:
                return HttpResponse("failure")

        # see if the user can edit the project
        try:
                user_project = user.Projects.get(project=project)
        except:
                return HttpResponse("failure")

        if len(user_project.permission.filter(id=8)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to create a report in this project")

        if request.method == "POST":
		# save report
		jid = int(request.POST['jid'])	
		job = project.Jobs.get(id=jid)
		name = string.strip(request.POST['name'])
		rid = int(request.POST['rid'])
		algo = ReportGenerator.objects.get(id=rid)
		permission = int(request.POST['permission'])
		if permission not in [0, 1, 2]:
                        permission = 0
		shared_report = user.SharedObjectsOwned.create(SharedObjectType=SharedObjectType.objects.get(id=8), description="Shared Report", sharing_permission=permission)

		project.Reports.create(name=name, user=user, job=job, reportgenerator=algo, shared_object=shared_report)
		return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(pid))
	else:
		jobs = project.Jobs.filter(status=1)
		algos = project.ReportGenerator_Algo_Uploaded.filter(status=1) | ReportGenerator.objects.filter(status=1, user=None, project=None)
		return render_to_response('TextBadger/newreport.html', locals())


@loginRequired
def editAlgo(request):
	user = getLoggedInUser(request)
	try:
                aid = request.GET['aid']
		type = request.GET['type']
		if type == 'r':
	                upid = 9
        	        algo = ReportGenerator.objects.get(id=int(aid))
        	elif type == 'c':
        	        upid = 10
        	        algo = Classifier_Algo.objects.get(id=int(aid))
        	else:
               		upid = 11
                	algo = Vectorizer_Algo.objects.get(id=int(aid))

                project = algo.project
                user_project = user.Projects.get(project=project)
	except:
                raise Http404

        if len(user_project.permission.filter(id=upid)) == 0 and len(user_project.permission.filter(id=1)) == 0 :
                return HttpResponse("You are not authorized to edit this algo in this project")

        if request.method == "POST":
                #save
                name = string.strip(request.POST['name'])
                permission = int(request.POST['permission'])
		if 'codefile' in request.FILES:
	                codefile = request.FILES['codefile']
			content_type = codefile.content_type
	                if content_type:
        	            main, sub = content_type.split('/')
                	    if not (main == 'text'):
                        	return HttpResponse('Please submit a valid ASCII Text File')
		else:
			codefile = None
                if permission not in [0, 1, 2]:
                        permission = 0

                try:
			algo.name = name
			if codefile != None:
				algo.filename = codefile
				algo.status = 2
			algo.shared_object.sharing_permission = permission
			algo.shared_object.save()
			algo.save()
                except:
                        return HttpResponse("Encountered an Error. Did you upload a valid code file in ASCII Text format?")

                return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))
        else:
                #show page
                return render_to_response("TextBadger/editalgo.html", locals())

@loginRequired
def viewTask(request):
	user = getLoggedInUser(request)

	if request.method == "POST":
		try:
	        	taskid = int(request.GET['tid'])
			docid = int(request.GET['docid'])
			task = Task.objects.get(id=taskid, user=user)
			corpus = task.corpus
			codebook = task.codebook
			if corpus.status != 1 or codebook.status != 1:
				return HttpResponseRedirect("Either the corpus or the codebook associated with this task has become inactive. Please wait for them to be active again")

			project = task.project
			doc = corpus.Documents.get(id=docid)
			# save task and redirect
			if len(task.DocumentResponses.filter(document=doc)) == 0:
				td = task.DocumentResponses.create(document=doc)
				for k, v in request.POST.lists():
					qtype = int(k[0])
					qid = int(k[2:])
					if qtype == 1:
						label = td.Labellings.create(codebook_question=Codebook_Question.objects.get(id=qid), coded_value=v[0])
					elif qtype == 2:
						label = td.Labellings.create(codebook_question=Codebook_Question.objects.get(id=qid), coded_choice=Codebook_Question_Choice.objects.get(id=int(v[0])))
					else:
						label = td.Labellings.create(codebook_question=Codebook_Question.objects.get(id=qid))
						for cid in v:
							label.coded_choices.add(Codebook_Question_Choice.objects.get(id=int(cid)))
			
				task.num_docs_completed = task.num_docs_completed + 1
				task.save()
			
			return HttpResponseRedirect(settings.ROOT_URL + 'task/?tid=' + str(taskid))
		except:
			return HttpResponseRedirect(settings.ROOT_URL + 'task/?tid=' + str(taskid))
	try:
		taskid = request.GET['tid']
		task = Task.objects.get(id=int(taskid), user=user)
		project = task.project
		corpus = task.corpus
		codebook = task.codebook
		minr = task.minrange-1
		maxr = task.maxrange
		documents = corpus.Documents.all().order_by('id')[minr:maxr]
		docs_completed_ids = task.DocumentResponses.values_list('document', flat=True).order_by('document')
		docs_completed = Document.objects.filter(id__in=list(docs_completed_ids))
	
		document = None
		for doc in documents:
			if doc not in docs_completed:
				document = doc
				docurl = settings.ROOT_URL + document.filename.url[1:]
				break
		
		if document == None:
			# Task is completed, return to project
			task.status = 1
			task.save()
			return HttpResponseRedirect(settings.ROOT_URL + 'project/?pid=' + str(project.id))

		Questions = codebook.Questions.all().order_by('id')					
		if corpus.status != 1 or codebook.status != 1:
			isHiddenTask = True
	except:
		isHiddenTask = True
	
	return render_to_response("TextBadger/task.html", locals())

